import { Controller } from 'egg';
import { Result, Token } from '../util';

class ManagerController extends Controller {
  // 验证登录并生成Token
  async authorization() {
    const { ctx } = this;

    // 获取用户传递的参数
    const { name, password } = ctx.query;

    // 校验参数
    ctx.validate({
      name: { type: 'string', allowEmpty: false },
      password: {
        type: 'password', allowEmpty: false, min: 6
      },
    }, ctx.query);

    const manager = await this.ctx.service.manager.findManagerByNameAndPassword(
      name,
      password
    );

    if (manager) {
      const { uuid } = manager;
      const jwtToken = await Token.createToken({ uuid });

      ctx.body = new Result({
        token: jwtToken,
      });
    } else {
      ctx.status = 422;
      ctx.body = new Result(undefined, '用户不存在或密码错误，请注册账号或修改密码');
    }
  }

  async update() {
    const { ctx } = this;

    ctx.validate({
      originalPassword: {
        type: 'password', allowEmpty: false, min: 6
      },
      newPassword: {
        type: 'password', allowEmpty: false, min: 6
      }
    }, ctx.request.body);

    const { originalPassword, newPassword } = ctx.request.body;
    // 这里的ctx.user.uuid使用了egg-passportde api
    const password = await this
      .ctx
      .service
      .manager
      .findPasswordByUuid(ctx.user.uuid);

    if (originalPassword !== password) {
      ctx.status = 422;
      ctx.body = new Result({ originalPasswordMatch: false }, '原始密码错误');
      return;
    }
    // 这里的ctx.user.id使用了egg-passportde api
    const changedPassword = await this
      .ctx.service.manager.changePassword(
        ctx.user.uuid,
        newPassword
      );

    ctx.body = new Result({ changedPassword });
  }
}

module.exports = ManagerController;
